package com.ciwong.epaper.modules.homework.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.TimeoutError;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.clazz.bean.TeacherClassBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.homework.adapter.TeacherWorkAdapter;
import com.ciwong.epaper.modules.homework.adapter.WorkClazzAdapter;
import com.ciwong.epaper.modules.homework.bean.PublishWorkRecords;
import com.ciwong.epaper.modules.me.bean.FollowTeacher;
import com.ciwong.epaper.modules.me.bean.PublishWorkRecordsPageBean;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.CWPopMenu;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 作业列表首页
 */
public class TeacherWorkFragment extends BaseFragment implements PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener, ExpandableListView.OnGroupClickListener,
        ExpandableListView.OnChildClickListener, View.OnClickListener {


    private TextView tea_add_work_text;
    //发布的作业列表
    private List<PublishWorkRecords> publishWorkRecords;

    private PullToRefreshView my_work_refresh_view;

    private ExpandableListView my_work_exlistv;

    private TeacherWorkAdapter teacherWorkAdapter;

    private RelativeLayout handle_go_to_bookdesk;

    private LinearLayout publish_work_lay;

    private RelativeLayout publish_work_parent_lay;


    private ListView class_name_list;

    private List<TeacherClassBean> teacherClassBeans;
    private final int defult_page = 1;

    private TextView dk_work_publish;

    private List<FollowTeacher> followTeacherList = new ArrayList<>();

    /**
     * 当前页码
     */
    private int curPage = defult_page;

    private int mPageCount = -1;

    /**
     * workStatus：0获取所有作业；1获取机房未过期作业（监考用）；2获取机房所有作业；3获取练习和考试作业
     */
    private int workStatus;

    //选择时间控件
    private TimePickerView pvTime;

    private int checkDate = 0;

    private TextView start_date_text;
    private TextView end_date_text;
    private RelativeLayout clean_time_text;
    private RelativeLayout agree_lay;
    //选中时间
    private long startTime;
    private long endTime;
    private long nextstartTime;
    private long nextendTime;
    private String chooseClassName;
    /**
     * 当前是否选中班级
     */
    private int classId = 0;
    /**
     * 时间选中
     */
    private RelativeLayout choose_time_lay;
    private TextView time_text;
    /**
     * 班级选择
     */
    private RelativeLayout choose_class_lay;
    private TextView class_name_text;

    private RelativeLayout choose_time_relative;
    private CheckBox choose_work_select;
    private boolean isFirst = false;

    /**
     * 默认加载数据大小
     */
    private static final int LOAD_PAGE_SIZE = 20;
    /**
     * 选择班级
     */
    private CWPopMenu mAddPopMenu;

    /**
     * 是否查看本学期
     */
    boolean isCurrentDataWork = false;

    public static TeacherWorkFragment newInstance() {
        TeacherWorkFragment teacherWorkFragment = new TeacherWorkFragment();
        return teacherWorkFragment;
    }


    public void onEventMainThread(EventBusFactory.ReflushWorkEvent reflushWorkEvent) {
        int examMode = reflushWorkEvent.getExamMode();
        if (workStatus == 2 && examMode == 1) {
            //机房作业有更新
            curPage = 1;
            getPublishWorkRecords(curPage);
        } else if (workStatus == 3 && examMode != 1) {
            //课后作业有更新
            curPage = 1;
            getPublishWorkRecords(curPage);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        workStatus = bundle.getInt("workStatus");
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_work, container, false);
        initView(view);
        init();
        return view;
    }

    protected void initView(View view) {
        //tea_add_work_text = view.findViewById(R.id.tea_add_work_text);
        my_work_refresh_view = view.findViewById(R.id.my_work_refresh_view);
        my_work_exlistv = view.findViewById(R.id.my_work_exlistv);
        publish_work_lay = view.findViewById(R.id.publish_work_lay);
        handle_go_to_bookdesk = view.findViewById(R.id.handle_go_to_bookdesk);
        publish_work_parent_lay = view.findViewById(R.id.publish_work_parent_lay);
        choose_class_lay = view.findViewById(R.id.choose_class_lay);
        class_name_text = view.findViewById(R.id.class_name_text);
        choose_time_lay = view.findViewById(R.id.choose_time_lay);
        start_date_text = view.findViewById(R.id.start_date_text);
        end_date_text = view.findViewById(R.id.end_date_text);
        clean_time_text = view.findViewById(R.id.clean_time_text);
        agree_lay = view.findViewById(R.id.agree_lay);
        choose_time_relative = view.findViewById(R.id.choose_time_relative);
        time_text = view.findViewById(R.id.time_text);
        choose_work_select = view.findViewById(R.id.choose_work_select);
        getCurrentDataWork();
        getPublishWorkRecords(curPage);
        getFollowTeachers();
        getMyClass(EApplication.BRAND_ID + "", 2, EApplication.getInstance().getMySchool().getSchoolId());
    }


    protected void init() {
        teacherWorkAdapter = new TeacherWorkAdapter(mActivity, publishWorkRecords);
        my_work_refresh_view.setOnHeaderRefreshListener(this);
        my_work_refresh_view.setOnFooterRefreshListener(this);
        my_work_exlistv.setAdapter(teacherWorkAdapter);
        choose_work_select.setSelected(true);
        agree_lay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                choose_work_select.setChecked(false);
                startTime = nextstartTime;
                endTime = nextendTime;
                showCricleProgress();
                curPage = 1;
                getPublishWorkRecords(curPage);
                if (startTime == 0 && endTime == 0) {
                    time_text.setTextColor(mActivity.getResources().getColor(R.color.black));
                } else {
                    time_text.setTextColor(mActivity.getResources().getColor(R.color.title_color));
                }
                choose_time_relative.setVisibility(View.GONE);
            }
        });
        clean_time_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                start_date_text.setText(getString(R.string.choose_date));
                startTime = 0;
                end_date_text.setText(getString(R.string.choose_date));
                endTime = 0;
                checkDate = 0;
            }
        });

        start_date_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTime(start_date_text, true);
                if (null != pvTime) {
                    pvTime.show();
                }
            }
        });

        end_date_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setTime(end_date_text, false);
                if (null != pvTime) {
                    pvTime.show();
                }
            }
        });
        choose_class_lay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mAddPopMenu != null) {
                    mAddPopMenu.showAsDropDown(choose_class_lay, (choose_class_lay.getWidth() + 80),
                            DeviceUtils.getScreenHeight() / 2);
                }
            }
        });

        choose_time_lay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (choose_time_relative.getVisibility() == View.VISIBLE) {
                    choose_time_relative.setVisibility(View.GONE);
                } else {
                    choose_time_relative.setVisibility(View.VISIBLE);
                }
            }
        });

        my_work_exlistv.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener()

        {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return true;
            }
        });
        choose_work_select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()

        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if (choose_time_relative.getVisibility() == View.VISIBLE) {
                    choose_time_relative.setVisibility(View.GONE);
                }
                if (buttonView.isPressed()) {
                    if (isChecked) {
                        //选中
                        checkDate = 1;
                        isCurrentDataWork = true;
                    } else {
                        //取消选中
                        checkDate = 0;
                        isCurrentDataWork = false;
                        time_text.setTextColor(mActivity.getResources().getColor(R.color.black));
                    }
                    showCricleProgress();
                    getCurrentDataWork();
                    curPage = 1;
                    getPublishWorkRecords(curPage);
                }
            }
        });
    }

    @Override
    public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
        return false;
    }

    @Override
    public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
        return false;
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        curPage = 1;
        getPublishWorkRecords(curPage);
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        if (!NetworkUtils.isOnline()) {
            CWToast.makeText(mActivity, getString(R.string.connect_disable), Toast.LENGTH_LONG).setToastType(CWToast.TOAST_TYPE_ERROR).show();
            return;
        }
        curPage++;
        getPublishWorkRecords(curPage);

    }

    /**
     * 获取班级列表
     */
    public void getMyClass(String brandId, int userRole, int schoolId) {
        EpaperDao.getInstance().getMyClass(brandId, userRole, schoolId, new BaseExtCallBack(getActivity(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    if (!NetworkUtils.isOnline()) {
                        ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                        return;
                    }
                }
            }

            @Override
            public void failed(Object data) {
                //hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void success(Object data) {
                if (null != data && data instanceof ArrayList) {
                    teacherClassBeans = (List<TeacherClassBean>) data;
                    addChooseClassPopMenu(teacherClassBeans);
                }
            }
        });
    }


    /**
     * 设置日期
     *
     * @param textView
     * @param isStartTime
     */
    private void setTime(final TextView textView, final boolean isStartTime) {
        //控制时间范围
        Calendar selectedDate = Calendar.getInstance();
        final Calendar startDate = Calendar.getInstance();
        //获取当前年月日时分
        startDate.set(2019, 1, 1, 00, 01);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2029, 11, 28, 23, 59);
        pvTime = new TimePickerBuilder(mActivity, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                checkDate = 1;
                if (isStartTime) {
                    nextstartTime = date.getTime() / 1000;
                    startTime = nextstartTime;
                } else {
                    nextendTime = date.getTime() / 1000;
                    endTime = nextendTime;
                }

                textView.setText(getTimes(date));
            }
        }).setType(new boolean[]{true, true, true, true, true, false})//年月日时分秒 的显示与否，不设置则默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")
                .isCenterLabel(true)
                .setContentTextSize(16)//字号
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .build();
    }

    /**
     * 日期格式化
     *
     * @param date
     * @return
     */
    private String getTimes(Date date) {//年月日时分格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }


    /**
     * 获取关注老师列表
     */
    private void getFollowTeachers() {
        EpaperDao.getInstance().getFollowTeachers(EApplication.BRAND_ID, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

            }

            @Override
            public void failed(Object data) {
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                }
            }

            @Override
            public void success(Object data) {
                if (null != data) {
                    followTeacherList = (List<FollowTeacher>) data;
                }
            }
        });
    }


    /**
     * 获取作业记录
     *
     * @param curPage
     */
    private void getPublishWorkRecords(int curPage) {
        EpaperDao.getInstance().getPublishWorkRecords(EApplication.BRAND_ID, workStatus, classId, checkDate, startTime, endTime,
                curPage, LOAD_PAGE_SIZE, new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
                    @Override
                    public void failed(int errorCode, Object data) {
                        hideCricleProgress();
                        my_work_refresh_view.onFooterRefreshComplete();
                        my_work_refresh_view.onHeaderRefreshComplete();
                        super.failed(errorCode, data);
                        failed(data);
                    }

                    @Override
                    public void failed(Object data) {
                        hideCricleProgress();
                        my_work_refresh_view.onFooterRefreshComplete();
                        my_work_refresh_view.onHeaderRefreshComplete();
                        if (data instanceof TimeoutError) {
                            hideCricleProgress();
                            ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                        }
                    }

                    @Override
                    public void success(Object data) {
                        hideCricleProgress();
                        my_work_refresh_view.onFooterRefreshComplete();
                        my_work_refresh_view.onHeaderRefreshComplete();
                        if (null != data) {
                            PublishWorkRecordsPageBean publishWorkRecordsPageBean = (PublishWorkRecordsPageBean) data;
                            setWorkList(publishWorkRecordsPageBean);
                        }
                    }
                });
    }

    /**
     * 筛选作业记录
     *
     * @param className 班级名
     * @param keyWord   关键字
     * @param period    时间段
     */
    private void filterWorkRecorder(String className, String keyWord, String period) {

    }

    /**
     * 设置作业列表
     *
     * @param publishWorkRecordsPageBean
     */
    private void setWorkList(PublishWorkRecordsPageBean publishWorkRecordsPageBean) {
        try {
            List<PublishWorkRecords> pageList = publishWorkRecordsPageBean.getPageList();
            int totalCount = publishWorkRecordsPageBean.getTotalCount();
            if (0 == totalCount) {
                handle_go_to_bookdesk.setVisibility(View.VISIBLE);
                publish_work_lay.setVisibility(View.GONE);
            } else {
                publishWorkRecords = pageList;
                handle_go_to_bookdesk.setVisibility(View.GONE);
                publish_work_lay.setVisibility(View.VISIBLE);
                if (curPage == 1) {
                    teacherWorkAdapter.clear();
                    init();

                } else {
                    teacherWorkAdapter.addAll(pageList);
                }
                for (int i = 0; i < teacherWorkAdapter.getGroupCount(); i++) {
                    my_work_exlistv.expandGroup(i);
                }
                if (teacherWorkAdapter.getGroupCount() == publishWorkRecordsPageBean.getTotalCount()) {
                    my_work_refresh_view.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                } else {
                    my_work_refresh_view.setFooterState(PullToRefreshView.PULL_TO_REFRESH);
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        /*if (id == R.id.tea_add_work_text) {
            MeJumpManager.jumpToFavoritesListActivity(mActivity, R.string.go_back);
        }*/
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 设置本学期
     */
    private void getCurrentDataWork() {
        if (isCurrentDataWork) {
            checkDate = 1;
            Calendar calendar = Calendar.getInstance();  //获取当前时间，作为图标的名字
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            Calendar startDate = Calendar.getInstance();
            Calendar endDate = Calendar.getInstance();
            if (month > 1 && month < 7) {
                //上学期范围2月1日-6月30
                startDate.set(year, 1, 1, 00, 00);
                endDate.set(year, 5, 30, 23, 59);
            } else {
                if (month == 1) {
                    //下学期范围7月1日-1月30
                    startDate.set((year - 1), 6, 1, 00, 00);
                    endDate.set(year, 0, 30, 23, 59);
                } else {
                    //下学期范围7月1日-1月30
                    startDate.set(year, 6, 1, 00, 00);
                    endDate.set((year + 1), 0, 30, 23, 59);
                }
            }
            startTime = startDate.getTimeInMillis() / 1000;
            endTime = endDate.getTimeInMillis() / 1000;
        } else {
            checkDate = 0;
            choose_work_select.setChecked(false);
        }
    }

    /**
     * 选择班级框
     *
     * @param teacherClassList
     */
    public void addChooseClassPopMenu(List<TeacherClassBean> teacherClassList) {
        List<CWPopMenu.PopMenuInfo> popMenuInfos = new ArrayList<CWPopMenu.PopMenuInfo>();
        CWPopMenu.PopMenuInfo popMenuInfo = new CWPopMenu.PopMenuInfo();
        popMenuInfo.setPopMenuName("全部班级");
        popMenuInfo.setPopMenuTag(0);
        popMenuInfos.add(popMenuInfo);

        for (int i = 0; i < teacherClassList.size(); i++) {
            CWPopMenu.PopMenuInfo popMenuInfoItem = new CWPopMenu.PopMenuInfo();
            popMenuInfoItem.setPopMenuName(teacherClassList.get(i).getClassName());
            popMenuInfoItem.setPopMenuTag(teacherClassList.get(i).getClassId());
            popMenuInfos.add(popMenuInfoItem);
        }
        mAddPopMenu = new CWPopMenu(getActivity(), popMenuInfos);
        mAddPopMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                CWPopMenu.PopMenuInfo popMenuInfoItem = (CWPopMenu.PopMenuInfo) parent.getAdapter().getItem(position);
                classId = popMenuInfoItem.getPopMenuTag();
                class_name_text.setText(popMenuInfoItem.getPopMenuName());
                isFirst = true;
                if (isFirst) {
                    showCricleProgress();
                    curPage = 1;
                    getPublishWorkRecords(1);
                }
                mAddPopMenu.dismiss();
            }
        });
    }
}
